package ua.at.tsvetkov.samizdat.activities;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import ua.at.tsvetkov.samizdat.Const;
import ua.at.tsvetkov.samizdat.R;
import ua.at.tsvetkov.samizdat.Utils;
import ua.at.tsvetkov.samizdat.adapters.AdtTextFlipper;
import ua.at.tsvetkov.samizdat.adapters.AdtTextListView;
import ua.at.tsvetkov.samizdat.database.ContentProviderSamizdat;
import ua.at.tsvetkov.samizdat.services.SrvTextDownload;
import ua.at.tsvetkov.samizdat.services.SrvUpdate;
import ua.at.tsvetkov.util.Log;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.Layout;
import android.text.Spanned;
import android.view.Display;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class AcTextFlipper extends Activity /* implements OnTouchListener */{

	// private Integer totalPages = 0;
	private ViewPager			flipper;
	private ListView			listView;
	private Cursor				resultCursor;

	private String				clickedTitle;

	private int					currentClickeBook;
	private ProgressDialog	bookLoadingDialog;

	private Float				fromPosition;
	private Float				toPosition;

	private int					maxLineCount;
	private Spanned			currentText;

	private int					viewFlipperChildCount;
	private int					viewFlipperCurrentChild	= 0;

	private volatile int		semaphore					= 0;

	// private int start;
	// private int end;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.ac_text_flipper);
		setContentView(R.layout.ac_text_flipper_list_view);
		// flipper = new ViewPager(this);
		// setContentView(flipper);
		listView = (ListView) findViewById(R.id.ac_text_flipper_list_view);
		// flipper.setOnTouchListener(this);
		bookLoadingDialog = new ProgressDialog(this);
		bookLoadingDialog.setCancelable(false);
		bookLoadingDialog.setIndeterminate(true);
		IntentFilter intentFilter = new IntentFilter(Const.BROADCAST_MESSAGE);
		registerReceiver(intentReceiver, intentFilter);

		Intent receivedIntent = getIntent();
		clickedTitle = receivedIntent.getStringExtra(Const.FRAGMENT_BOOKS_CLICK_TITLE);

		new Thread(new Runnable() {
			@Override
			public void run() {

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						bookLoadingDialog.setTitle("Отображение книги");
						bookLoadingDialog.setMessage("Подождите, происходит поиск книги...");
						if (!bookLoadingDialog.isShowing()) {
							bookLoadingDialog.show();
						}
					}
				});

				resultCursor = getContentResolver().query(Uri.parse(ContentProviderSamizdat.BOOK_CONTENT_URI + "/"), new String[] { Const.OBJECT, Const.BOOK_PATH, Const.ID },
						Const.TITLE + "=" + "'" + clickedTitle + "'", null, null);
				resultCursor.moveToFirst();

				currentClickeBook = resultCursor.getInt(2);

				if (resultCursor.getString(1).equals("")) {

					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							bookLoadingDialog.setTitle("Отображение книги");
							bookLoadingDialog.setMessage("Подождите, происходит скачивание...");
							if (!bookLoadingDialog.isShowing()) {
								bookLoadingDialog.show();
							}
						}
					});

					Intent srvTextDownload = new Intent(AcTextFlipper.this, SrvTextDownload.class);
					srvTextDownload.putExtra("BOOK_URL", resultCursor.getString(0));
					srvTextDownload.putExtra("BOOK_ID", resultCursor.getInt(2));
					startService(srvTextDownload);
				} else {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							bookLoadingDialog.setMessage("Подождите, происходит загрузка с носителя...");
							if (!bookLoadingDialog.isShowing()) {
								bookLoadingDialog.show();
							}
						}
					});
					updateUIListView();
				}
			}
		}).start();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private void updateUIListView() {
		final String[] text = getTextFromFile(Utils.getHomeDirectoryPath(AcTextFlipper.this) + String.valueOf(currentClickeBook) + ".txt").split("<br>");
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				listView.setFocusable(false);
				listView.setDivider(null);
				listView.setDividerHeight(0);
				listView.setAdapter(new AdtTextListView(AcTextFlipper.this, text));
				bookLoadingDialog.dismiss();
			}
		});
	}

	private void updateUIFlipper() {
		List<View> views = new ArrayList<View>();
		TextView t1 = new TextView(this);
		TextView t2 = new TextView(this);

		t1.setBackgroundColor(Color.RED);
		views.add(t1);
		views.add(t2);
		AdtTextFlipper pagerAdapter = new AdtTextFlipper(views, Html.fromHtml(getTextFromFile(Utils.getHomeDirectoryPath(AcTextFlipper.this) + String.valueOf(currentClickeBook) + ".txt")), this);
		flipper.setAdapter(pagerAdapter);
		flipper.setOnPageChangeListener(pagerAdapter);
		flipper.setCurrentItem(1);

		bookLoadingDialog.dismiss();
		// new Thread(new Runnable() {
		// @Override
		// public void run() {
		// Display display = getWindowManager().getDefaultDisplay();
		// final int screenWidth = display.getWidth();
		// final int screenHeight = 1097;
		// currentText = Html.fromHtml(getTextFromFile(Utils.getHomeDirectoryPath(AcTextFlipper.this) + String.valueOf(currentClickeBook) + ".txt"));
		//
		// while (currentText.length() != 0) {
		// final TextView contentTextView = new TextView(AcTextFlipper.this);
		// contentTextView.setHeight(screenHeight);
		// contentTextView.setWidth(screenWidth);
		// maxLineCount = (screenHeight) / contentTextView.getLineHeight();
		// contentTextView.setLines(maxLineCount);
		// contentTextView.setMaxLines(maxLineCount);
		//
		// // contentTextView.setText(Html.fromHtml(currentText));
		// contentTextView.setText(currentText);
		// // Log.e("Vivodim " + currentText);
		// // Log.e("length " + currentText.length());
		//
		// runOnUiThread(new Runnable() {
		// @Override
		// public void run() {
		// flipper.addView(contentTextView);
		// bookLoadingDialog.dismiss();
		// }
		// });
		//
		// while (contentTextView.getLayout() == null) {
		// try {
		// Thread.sleep(400);
		// } catch (Exception e) {
		// }
		// }
		//
		// final int start = contentTextView.getLayout().getLineStart(0);
		// if (maxLineCount > contentTextView.getLineCount()) {
		// maxLineCount = contentTextView.getLineCount();
		// }
		//
		// int tmp;
		// if (currentText.length() > contentTextView.getLayout().getLineEnd(maxLineCount - 1)) {
		// tmp = contentTextView.getLayout().getLineEnd(maxLineCount - 1);
		// } else {
		// tmp = currentText.length();
		// }
		// final int end = tmp;
		// runOnUiThread(new Runnable() {
		// @Override
		// public void run() {
		// contentTextView.setText(currentText.subSequence(start, end));
		// semaphore = 1;
		// }
		// });
		// while (semaphore == 0) {
		// try {
		// Thread.sleep(300);
		// } catch (Exception e) {
		// }
		// }
		// semaphore = 0;
		// currentText = (Spanned) currentText.subSequence(end, currentText.length());
		// }
		// }
		// }).start();
	}

	// @Override
	// public boolean onTouch(View view, MotionEvent event) {
	// flipper.getMeasuredHeight();
	// flipper.getMeasuredWidth();
	//
	// switch (event.getAction()) {
	// case MotionEvent.ACTION_DOWN:
	// fromPosition = event.getX();
	// break;
	// case MotionEvent.ACTION_UP:
	// toPosition = event.getX();
	// if (fromPosition > toPosition) {
	// flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.go_next_in));
	// flipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.go_next_out));
	// viewFlipperChildCount = flipper.getChildCount();
	// viewFlipperCurrentChild++;
	// if (viewFlipperCurrentChild == viewFlipperChildCount) {
	// viewFlipperCurrentChild = viewFlipperChildCount - 1;
	// } else {
	// flipper.showNext();
	// }
	// } else {
	// flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.go_prev_in));
	// flipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.go_prev_out));
	// viewFlipperChildCount = flipper.getChildCount();
	// viewFlipperCurrentChild--;
	// if (viewFlipperCurrentChild == -1) {
	// viewFlipperCurrentChild = 0;
	// } else {
	// flipper.showPrevious();
	// }
	// }
	//
	// default:
	// break;
	// }
	// return true;
	// }

	private String getTextFromFile(String path) {
		try {
			BufferedReader reader = new BufferedReader(new FileReader(path));
			String line, results = "";
			while ((line = reader.readLine()) != null) {
				results += line;
			}
			reader.close();
			return results;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main_activity_menu, menu);

		MenuItem settings = menu.findItem(R.id.main_menu_settings);
		
		MenuItem updateBooks = menu.findItem(R.id.main_menu_update);
		updateBooks.setVisible(false);
		
		MenuItem sortByBall = menu.findItem(R.id.main_menu_sort_by_ball);
		sortByBall.setVisible(false);
		
		MenuItem sortByDate = menu.findItem(R.id.main_menu_sort_by_date);
		sortByDate.setVisible(false);
		
		SearchView searchView = (SearchView) menu.findItem(R.id.main_menu_search).getActionView();
		searchView.setVisibility(View.GONE);

		settings.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {
				startActivity(new Intent(AcTextFlipper.this, PrefAcSamizdat.class));
				return false;
			}
		});
		
		return true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(intentReceiver);
	}

	BroadcastReceiver	intentReceiver	= new BroadcastReceiver() {
													@Override
													public void onReceive(Context context, Intent intent) {
														String serviceTextDownloadStoped = intent.getStringExtra(Const.SERVICE_TEXT_DOWNLOAD_STOPED);
														String serverIsUnavailable = intent.getStringExtra(Const.SERVER_IS_UNAVAILABLE);
														if (serviceTextDownloadStoped != null) {
															// updateUIFlipper();
															updateUIListView();
														}
														if (serverIsUnavailable != null) {
															bookLoadingDialog.dismiss();
															AlertDialog.Builder serverUnavailableAlert = new AlertDialog.Builder(AcTextFlipper.this);
															serverUnavailableAlert.setTitle("Ошибка загрузки!");
															serverUnavailableAlert.setMessage("В данный момент сервер недоступен.");
															serverUnavailableAlert.setPositiveButton("OK", new OnClickListener() {

																@Override
																public void onClick(DialogInterface dialog, int which) {
																	dialog.cancel();
																	AcTextFlipper.this.finish();
																}
															});
															serverUnavailableAlert.show();
														}
													}
												};
}
